package device

import (
	"backend/internal/common/errorx"
	"context"
	"fmt"
	"net/http"

	"backend/internal/svc"
	"backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CloseConnectionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCloseConnectionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CloseConnectionLogic {
	return &CloseConnectionLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CloseConnectionLogic) CloseConnection(req *types.CloseConnectionReq) (resp *types.CloseConnectionResp, err error) {
	// 获取设备
	client := l.svcCtx.ClientManager.GetClient(req.DeviceName)
	if client == nil {
		errorStr := fmt.Sprintf("设备 %s 不存在", req.DeviceName)
		logx.Errorf(errorStr)
		return nil, errorx.NewCodeError(http.StatusNotFound, "无法找到该设备")
	}

	// 断开设备连接
	client.Disconnect()

	// 返回成功响应
	resp = &types.CloseConnectionResp{
		Status: http.StatusOK,
		Msg:    "成功断开设备连接",
		Data:   true,
	}
	return resp, nil
}
